﻿using System;
using System.Configuration;
using System.Data.Odbc;

namespace UPos.Core.DataDriver
{
    class DbOdbc : IDisposable
    {
        static string DefaultConnectionString { get; set; }

        static DbOdbc()
        {
            if (string.IsNullOrWhiteSpace(DefaultConnectionString))
            {
                var setting = ConfigurationManager.ConnectionStrings["odbc"];
                if (setting == null)
                    throw new ConfigurationErrorsException("ConnectionString 配置节，必须至少包含一个名为 odbc 的项");
                DefaultConnectionString = setting.ConnectionString;
            }
        }

        OdbcConnection CoreConn { get; set; }

        public DbOdbc()
        {
            CoreConn = new OdbcConnection(DefaultConnectionString);
            CoreConn.Open();
        }

        internal object ExecuteScalar(string sql, params OdbcParameter[] oracleParameters)
        {
            using (var cmd = CoreConn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(oracleParameters);
                return cmd.ExecuteScalar();
            }
        }

        internal OdbcDataReader ExecuteReader(string sql, params OdbcParameter[] oracleParameters)
        {
            using (var cmd = CoreConn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(oracleParameters);
                return cmd.ExecuteReader();
            }
        }

        public void Dispose()
        {
            CoreConn.Dispose();
        }
    }
}
